;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Purchase.PurchaseOrder", [])
        .controller("PurchaseOrderCtrl", ["$scope", "$state", "$stateParams", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, $stateParams, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            $scope.activeFlag = [true, false, false, false, false, false, false, false, false, false, false, false, false, false];
            $scope.detailFlag = [true, true];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.orgId = ''
            $scope.isJCHDlsh = false
            $scope.showPrice = true
            $scope.showAllPrice = true
            $scope.currentUserInfo = {
                isSap: false
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {
                seller: false
            };
            // 展示价格方案
            $scope.showPricePlan = true
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.deliveryWayList = [];
            $scope.detailInfo = {
                crucialDevice: 0,
                entranceDevice: 0
            };
            $scope.filterCondition = {};
            $scope.tabFlag = {};
            var tabFlag = {
                0: "采购申请详情",
                1: "新增采购申请",
                2: "编辑采购申请"
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/purchaseRequest/export"),
                sectionParam: {
                    billIds: []
                },
                allUrl: ybHttp.RequestUrl("device", "/purchaseRequest/exportAll")
            };         
            $scope.orderObj = {
                materialsList: [],
                materialNos4Plan: [],
                isDirectCast: 0,
                isSpecialOrder: 0,
                isImprove: 0,
                forward: 0
            };
            $scope.rowComPany = '';
            $scope.exportAddParam = {
                sectionParam: {
                    infoList: []
                },
                allUrl: ybHttp.RequestUrl("device", "/purchaseRequest/sapCheckInfoExport")
            };      
            $scope.purchaseLevelList = [];
            $scope.billStateList = [];
            $scope.isSap = false;
            $scope.detailMap = [{
                    name: '采购单号',
                    field: 'purchaseNo'
                },
                {
                    name: '接收单位',
                    field: 'supplierOrgName'
                },
                {
                    name: '采购级别',
                    field: 'purchaseLevel'
                },
                {
                    name: '订单状态',
                    field: 'auditState'
                },
                {
                    name: '审核意见',
                    field: 'auditState'
                },
                {
                    name: '采购方式',
                    field: 'purchaseType'
                },
                {
                    name: '发运方式',
                    field: 'dispatchWay'
                },
                {
                    name: '承运商',
                    field: 'dispatchCompany'
                },
                {
                    name: '类型',
                    field: 'type'
                },
                {
                    name: '调度员',
                    field: 'dispatcher'
                },
                {
                    name: '收货人',
                    field: 'receiver'
                },
                {
                    name: '联系人',
                    field: 'contact'
                },
                {
                    name: '传真',
                    field: 'fax'
                },
                {
                    name: '收货地址',
                    field: 'address'
                },
                {
                    name: '出库状态',
                    field: 'warehouseState'
                },
                {
                    name: '申请人',
                    field: 'apply'
                },
                {
                    name: '申请日期',
                    field: 'applyDate'
                },
                {
                    name: '申请部门',
                    field: 'applyDepart'
                },
                {
                    name: '申请人联系方式',
                    field: 'applyContact'
                },
                {
                    name: '备注',
                    field: 'remark'
                }
            ];
            $scope.tableConfig = {
                fixedWidth: 400,
                scrollWidth: 1400,
                tableCol: [
                    {
                        type: "",
                        name: "采购单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购合同号",
                        dataField: "purchaseContractNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "接收单位",
                        dataField: "supplierOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否直投订单",
                        dataField: "isDirectCastShow",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购方式",
                        dataField: "purchaseType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购组",
                        dataField: "purchaseGroup",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购金额",
                        dataField: "totalValue",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货方式",
                        dataField: "sendType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "submitDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditMessage",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购凭证",
                        dataField: "voucherNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synSap",
                        name: "同步状态",
                        dataField: "sapStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        clickFn: "viewSapError",
                        sortType: ""
                    },
                    {
                        type: "attach",
                        name: "附件",
                        dataField: "attachName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "downloadAttach",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购计划单号",
                        dataField: "buyPlanOrder",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否整改",
                        dataField: "isImproveShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购计划申请人",
                        dataField: "planCreateName",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "是否前移",
                        dataField: "forwardShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 400,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            // 新增内部表格
            $scope.materielTableConfig = {
                scrollWidth: 1780,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                    },
                    {
                        name: "原零件号",
                        width: 150,
                        dataField: "originalMaterialsNo",
                    },
                    {
                        name: "零件属性",
                        width: 150,
                        dataField: "productPropClass",
                    },               
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                    },
                    {
                        name: "零件英文描述",
                        width: 150,
                        dataField: "materialsDesEn",
                    },
                    {
                        name: "未发货数量",
                        width: 150,
                        dataField: "noDeliveredQty",
                        isShow: false 
                    },
                    {
                        name: "上次采购时间",
                        width: 150,
                        dataField: "lastPurchaseTime",
                        isShow:false
                    },
                    {
                        name: "本年度采购数量",
                        width: 150,
                        dataField: "thisYearPurchaseAmount",
                        isShow:false,
                    },
                    {
                        name: "行号",
                        width: 80,
                        dataField: "rowNo",
                        type: "rowNo",
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                    },
                    {
                        name: "适用机型",
                        width: 120,
                        dataField: "machineModel",
                        inputType: "machineModel",
                        needInput: true
                    },
                    {
                        name: "单价(￥)",
                        width: 120,
                        dataField: "price",
                        isShow: true
                    },
                    {
                        name: "价格方案",
                        width: 140,
                        dataField: "priceSchemeName",
                        needInput: true,
                        inputType: "func",
                    },
                    {
                        name: "成交单价(￥)",
                        width: 120,
                        dataField: "settlementPrice",
                    },
                    {
                        name: "可用库存",
                        width: 100,
                        dataField: "enableNum",
                    },
                    {
                        name: "其他经销商库存",
                        width: 100,
                        dataField: "otherDealerStock",
                        clickFn: 'qitaStock'
                    },
                    {
                        name: "外部库存",
                        width: 100,
                        dataField: "totalOuter",
                        isShow: !$scope.isZHJCH,
                        clickFn: 'waibuStock'
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: true
                    },
                    {
                        name: "净价",
                        width: 100,
                        dataField: "netPrice",
                        inputType: "netPrice",
                        needInput: true
                    },
                    {
                        name: "合计(￥)",
                        width: 150,
                        dataField: "applyTotalPrice",
                    },
                    {
                        name: "已建入库数量",
                        width: 100,
                        dataField: "sendQty",
                    },
                    {
                        name: "实际入库数量",
                        width: 100,
                        dataField: "realQty",
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: "deliveryDate",
                        needInput: true,
                        inputType: "time"
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo"
                    },
                    {
                        name: "替换零件中文名",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsDes"
                    },
                    {
                        name: "替换描述",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNote"
                    },                  
                    {
                        name: "备注",
                        width: 130,
                        dataField: "remark",
                        needInput: true,
                        inputType: "remark"
                    }, 
                    {
                        name: "标准交期",
                        width: 130,
                        dataField: "standDeliveryTime",
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                    },
                    {
                        name: "入库时间",
                        dataField: "inboundTimeShow",
                        width: 130,
                    },
                    {
                        name: "外部变更人",
                        dataField: "sapChangeName",
                        width: 130,
                        isShow:$scope.isJCHK,
                    },
                    {
                        name: "外部变更日期",
                        dataField: "sapChangeDate",
                        width: 130,
                        isShow:$scope.isJCHK,
                    }
                ]
            };

            $scope.materielPlanTableConfig = {
                scrollWidth: 1580,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "订单类型",
                        width: 100,
                        dataField: "orderTypeShow",
                        needInput: false
                    },
                    {
                        name: "采购组",
                        width: 100,
                        dataField: "purchaseGroup",
                        needInput: false
                    },
                    {
                        name: "计划供货商",
                        width: 100,
                        dataField: "supplierName",
                        needInput: false
                    },
                    {
                        name: "供货商",
                        width: 200,
                        dataField: "purchaseInfoVOList",
                        inputType: "select",
                        needInput: true
                    },
                    {
                        name: "sap返回信息",
                        width: 120,
                        dataField: "msg",
                        needInput: false
                    },                    
                    {
                        name: "出库频次",
                        width: 80,
                        dataField: "salesRate",
                        needInput: false
                    },
                    {
                        name: "计划数量",
                        width: 100,
                        dataField: "planAmount",
                        needInput: false
                    },
                    {
                        name: "创建订单数量",
                        width: 140,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: true
                    },
                    {
                        name: "交货日期",
                        width: 140,
                        dataField: "deliveryDate",
                        needInput: true,
                        inputType: "time"
                    },
                    {
                        name: "替换零件",
                        width: 120,
                        needWarn: true,
                        dataField: "replaceMaterialsNo"
                    },
                    {
                        name: "替换零件中文名",
                        width: 130,
                        needWarn: true,
                        dataField: "replaceMaterialsDes"
                    },
                    {
                        name: "替换描述",
                        width: 130,
                        needWarn: true,
                        dataField: "replaceMaterialsNote"
                    },
                    {
                        name: "备注",
                        width: 130,
                        dataField: "remark",
                        needInput: true,
                        inputType: "remark"
                    },
                    {
                        name: "计划剩余数量",
                        width: 150,
                        needWarn: true,
                        dataField: "remainingQty"
                    }
                ]
            };

            $scope.directMaterielTableConfig = {
                scrollWidth: 1450,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "参考单价(￥)",
                        width: 120,
                        dataField: "price",
                        needInput: false
                    },
                    {
                        name: "成交单价(￥)",
                        width: 120,
                        dataField: "settlementPrice",
                        input: true,
                        inputType: "settlementPrice",
                        needInput: true
                    },
                    {
                        type: "storage",
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: false
                    },
                    {
                        name: "净价",
                        width: 100,
                        dataField: "netPrice",
                        inputType: "netPrice",
                        needInput: true
                    },
                    {
                        name: "合计(￥)",
                        width: 150,
                        dataField: "applyTotalPrice",
                        needInput: false
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: "deliveryDateStr",
                        needInput: false
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo"
                    },
                    {
                        name: "替换零件中文名",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsDes"
                    },
                    {
                        name: "替换描述",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNote"
                    }
                ]
            };

            var btnPermissionCode = {
                purchaseOrderAdd: window.ActionCode.purchaseOrderAdd,
                purchaseOrderAutoAdd: window.ActionCode.purchaseOrderAutoAdd,
                purchaseOrderEdit: window.ActionCode.purchaseOrderEdit,
                purchaseOrderAdjust: window.ActionCode.purchaseOrderAdjust,
                purchaseOrderDel: window.ActionCode.purchaseOrderDel,
                purchaseOrderExport: window.ActionCode.purchaseOrderExport,
                purchaseOrderSAP: window.ActionCode.purchaseOrderSAP,
                purchaseOrderSapAdd: window.ActionCode.purchaseOrderSapAdd,
                purchaseOrderImport: window.ActionCode.purchaseOrderImport,
                purchaseOrderCancel: window.ActionCode.purchaseOrderCancel,
                purchaseOrderDirect: window.ActionCode.purchaseOrderDirect,
                purchaseOrderCreateBarcode: window.ActionCode.purchaseOrderBarcode,
                purchaseOrderViewLogistics: window.ActionCode.purchaseOrderViewLogistics,
                purchaseOrderWJ: window.ActionCode.purchaseOrderWJ,
                purchaseOrderAddFromSalesOrder: window.ActionCode.purchaseOrderAddFromSalesOrder,
                purchaseOrderBatchPrice: window.ActionCode.purchaseOrderBatchPrice,
            };

            $scope.btnPermission = {
                purchaseOrderAdd: true,
                purchaseOrderAutoAdd: true,
                purchaseOrderEdit: true,
                purchaseOrderAdjust: true,
                purchaseOrderDel: true,
                purchaseOrderExport: true,
                purchaseOrderSAP: true,
                purchaseOrderSapAdd: true,
                purchaseOrderImport: true,
                purchaseOrderCancel: true,
                purchaseOrderDirect: true,
                purchaseOrderCreateBarcode: true,
                purchaseOrderViewLogistics: true,
                purchaseOrderWJ: true,
                purchaseOrderAddFromSalesOrder: true,
                purchaseOrderBatchPrice: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: { left: $scope.tableConfig.fixedWidth + "px" },
                    scrollLeftWidth: { width: $scope.tableConfig.fixedWidth + "px" },
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false, false, false, false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        break;
                    case 4:
                        $scope.selectPlan.setFixedWidth();
                        break;
                    case 7:
                        $scope.directPurchasePlan.setFixedWidth();
                        break;
                    case 9:
                        $scope.barCodePage.detailInfo = {};
                        $scope.barCodePage.packList = [];
                        $scope.barCodePage.currentMaterial = {};
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    materialsList: [],
                    materialNos4Plan: [],
                    isDirectCast: 0,
                    isSpecialOrder: 0,
                    isImprove: 0,
                    forward: 0
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.detailFlag = [true, true];
                $scope.isSupplierWj = false;
                $scope.supplierOrgId = false;

                $scope.curStep = 0;
                $scope.orderCondition = {
                    status: 1,
                    notDirect: 1,
                    deliveryListFlag: 1,
                    purchaseListFlag: 1,
                };
                $scope.orderPageInfo = {
                    totalRows: 0,
                    totalPages: 1,
                    pageSize: 10,
                    curPage: 1
                };
                $scope.isFromExceptionSummary = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.billIds = [];
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                    filters: {
                        ...$scope.condition,
                        seller: false
                    }
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.submitDateShow = $filter("YbDate")(item.submitDate, 'yyyy-MM-dd HH:mm:ss');
                        item.sapStatusShow = $filter("ProgressStatus")(item.sapStatus, "sap");
                        item.isDirectCastShow = $filter("TrueOrFalse")(item.isDirectCast);
                        item.purchaseType = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                        item.sendType = item.sendTypeChildId ? item.shippingMethod + "-" + item.sendTypeChildName : item.shippingMethod;
                        item.isImproveShow = $filter("TrueOrFalse")(item.isImprove);
                        item.forwardShow = $filter("TrueOrFalse")(item.forward);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    case "downloadAttach":
                        downloadAttach(item);
                        break;
                    case "waibuStock":
                        waibuStock(item);
                        break;
                    case "qitaStock":
                        qitaStock(item);
                        break;
                    default:
                        break;
                }
            };

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            function downloadAttach(item) {
                window.location.href = ybHttp.RequestUrl("device", "/purchaseRequest/downloadAttach") + '?billId=' + item.billId;
            }

            function getPurchaseLevel() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "CGJB"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.purchaseLevelList = resp.value;
                })
            }

            function getOrderStatues() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "SPZT"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.billStateList = resp.value;
                })
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    seller: false
                };

                if ($scope.isJCHK) {
                    $scope.condition.countryVOS = $scope.curUser.associateCountryVOS;
                }
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };

            function getDetail(item, type) {
                var param = {
                    billId: item.billId
                };
                return ybHttp.Get('device', '/purchaseRequest/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (!resp.value) return null;
                    angular.forEach(resp.value.materialsList, function (item) {
                        item.oldQty = item.qty;
                        item.deliveryDate = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd');
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        item.inboundTimeShow = $filter("YbDate")(item.inboundTime, 'yyyy-MM-dd HH:mm:ss');

                        item.totalOuter = item?.outWarehouseVO?.totalOuter;
                        item.totalInner = item?.outWarehouseVO?.innerWarehouse;
                    });
                    resp.value.sapStatusShow = $filter("ProgressStatus")(resp.value.sapStatus, "sap");
                    
                    resp.value.billTypeMode = resp.value.billTypeMode || ''
                    resp.value.materialsType = resp.value.materialsType || ''
                    return resp.value;
                });
            }
            function setPriceSchemeBatch(item, index, priceScheme) {
                var settlementPrice;
                item.priceSchemeId = priceScheme.activityId;
                item.priceSchemeName = priceScheme.name;
                settlementPrice = $filter("decimalCover")(priceScheme.discountPrice, 2);
                $scope.orderObj.materialsList[index].settlementPrice = settlementPrice;
                if (item.qty !== "") {
                    setAdjustPrice(item, "qty");
                }
            }
            function setAdjustPrice(item, colItem) {
                item.qtyAdjustErr = false;
                item.priceAdjustErr = false;

                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyAdjustErr = true;
                    return;
                }
                if (!item.settlementPrice || parseFloat(item.settlementPrice) <= 0) {
                    item.priceAdjustErr = true;
                }
                if (item.qty > 9999999.999) {
                    item.qty = 9999999.999;
                }
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.applyTotalPrice = ""
                } else {
                    item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                }
                setTotalPriceAdjust();
            }

            function setTotalPriceAdjust() {
                var totalPrice = 0;
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    if (!item.applyTotalPrice) {
                        return false;
                    }
                    totalPrice = ybWidget.Plus(totalPrice, parseFloat(item.applyTotalPrice));
                });
                $scope.orderObj.settleValue = $filter("decimalCover")(totalPrice, 2);
                $scope.orderObj.totalValue = $scope.orderObj.settleValue;
            }

            function batchSetPriceScheme(priceSchemeId) {

                for (var i = 0; i < $scope.orderObj.materialsList.length; i++) {
                    var materialItem = $scope.orderObj.materialsList[i];
                    var priceSchemeList = materialItem.marketingActivityPriceVOList || [];
                    var priceScheme = getPriceScheme(priceSchemeId, priceSchemeList);
                    if (priceScheme != null) {
                        setPriceSchemeBatch(materialItem, i, priceScheme);
                    }
                }

                function getPriceScheme(id, list) {
                    for (var j = 0; j < list.length; j++) {
                        if (id == list[j].activityId) {
                            return list[j];
                        }
                    }
                    return null;
                }
            }

            $scope.batchChosePriceScheme = function () {
                var clientId = $scope.orderObj.supplierOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择接收单位');
                    return;
                }

                var param = {
                    isBatch: true,
                    schemeType: 1,
                    selectedDisabled: !$scope.isZHJCH && window.WJ_ORG_IDs.includes(clientId),
                    apiObj: {
                        param: {
                            supplierOrgId: clientId,
                            country: window.WJ_ORG_IDs.includes(clientId) ? $scope.orderObj.country : undefined
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    batchSetPriceScheme(data.id);
                });
            };
            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    if (window.WJ_ORG_IDs.includes(data.supplierOrgId)) {
                        $scope.isSupplierWj = true;
                    } else {
                        $scope.isSupplierWj = false;
                    }

                    $scope.orderObj = data;


                    if(window.JCH_ORG_IDs.includes(data.supplierOrgId)){
                        $scope.orgId = data.supplierOrgId
                    }else{
                        $scope.orgId = "";
                    }


                    $scope.isSupplierZx = judgeSupplierisZX($scope.orderObj.supplierOrgId);

                    $scope.orderObj.isPlatCompany = $scope.orderObj.platCompany;
                    $scope.orderObj.deliveryDate = $filter("YbDate")($scope.orderObj.deliveryDate, 'yyyy-MM-dd');
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.deliveryDate = item.deliveryDate.substring(0, 10);
                    });
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    if (item.billStatus === '2') {
                        $scope.changeTab(10);
                    } else {
                        $scope.changeTab(2);
                    }
                    // 接收单位是铲运的时候隐藏单价
                    hidePrice4jchkWhenSupplierIsCY()
                    hidePrice4jchkWhenSupplierIsWJ();


                });
            };
            $scope.adjustApply = function (item) {
                $scope.rowComPany = item.supplierOrgId
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }

                    if (window.WJ_ORG_IDs.includes(data.supplierOrgId)) {
                        $scope.isSupplierWj = true;
                    } else {
                        $scope.isSupplierWj = false;
                    }

                    $scope.orderObj = data;
                    console.log(data);
                    $scope.orderObj.isPlatCompany = $scope.orderObj.platCompany;
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.deliveryDate = item.deliveryDate.substring(0, 10);
                    });
                    $scope.changeTab(12);
                    // 接收单位是铲运的时候隐藏单价
                    hidePrice4jchkWhenSupplierIsCY()
                    hidePrice4jchkWhenSupplierIsWJ();
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.changeTab(3);
                    // 接收单位是铲运的时候隐藏单价
                    hidePrice4jchkWhenSupplierIsCY()
                    hidePrice4jchkWhenSupplierIsWJ('detail');
                });
            }

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialsList.splice(index, 1);
                    //采购订单创建的编辑需传值
                    if(!!$scope.orderObj.buyPlanOrder){
                        if(!$scope.orderObj.materialNos4Plan){
                            $scope.orderObj.materialNos4Plan = [item.materialsNo];
                        }else{
                            if(!$scope.orderObj.materialNos4Plan.includes(item.materialsNo)){
                                $scope.orderObj.materialNos4Plan.push(item.materialsNo);
                            }
                        }
                    } 
                        
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };
            $scope.reject = function (item) {
                var service = "device";
                var reqUrl = "/purchaseRequest/approveBuyPlanDetail";
                ybWidget.ShowConfirm("确定要驳回吗？", "驳回说明").then(function (note) {
                    var param = {
                        buyPlanOrder: $scope.orderObj.buyPlanOrder, // 采购计划单号
                        materialsNo: item.materialsNo, // 零件号
                        remark: note,
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            };        
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialsList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialsList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialsList[i].isChecked) {
                            var delMaterialsNo = $scope.orderObj.materialsList[i].materialsNo;
                            $scope.orderObj.materialsList.splice(i, 1);
                            //采购订单创建的编辑需传值
                            if(!!$scope.orderObj.buyPlanOrder){
                                if(!$scope.orderObj.materialNos4Plan){
                                    $scope.orderObj.materialNos4Plan = [delMaterialsNo];
                                }else{
                                    if(!$scope.orderObj.materialNos4Plan.includes(delMaterialsNo)){
                                        $scope.orderObj.materialNos4Plan.push(delMaterialsNo);
                                    }
                                }
                            } 
                        }
                    }
                    if ($scope.orderObj.materialsList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };
            $scope.batchCheck = function() {
                let arr = $scope.orderObj.materialsList.filter(item => item.isChecked == true)
                if (arr.length == '0') {
                    ybWidget.ShowMessage('请选择需要校验的行');
                    return
                }
                var service = "device";
                var reqUrl = "/sapSync/mantualCheck";
                ybHttp.Post(service, reqUrl, arr).then(function (resp) {
                    $scope.orderObj.materialsList.forEach(item => {
                        resp.value.forEach(el => {
                             if (item.materialsNo == el.materialsNo) {
                                item.msg = el.msg
                             }
                        });
                    });
                    getinfoList()
                });                
            }
            $scope.countTotal = function (item) {
                let num  = item.qtyNum - item.qty
                // 传入真实的计算数据
                item.realRemainingQty = num
                // 计划剩余数量显示数据
                item.remainingQty = num > 0 ? num : 0

                item.qtyErr = false;
                item.qtyFormatErr = false;
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                    item.qtyFormatErr = true;
                    return;
                }
                if (item.qty > 9999999.999) {
                    item.qty = 9999999.999;
                }
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            };

            $scope.countTotalEdit = function (item) {
                item.qtyErr = false;
                item.qtyFormatErr = false;
                item.qtyEditErr = false;
                item.qtyMaxErr = false;
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                    item.qtyFormatErr = true;
                    return;
                }
                if (item.qty < item.sendQty) {
                    item.qtyEditErr = true;
                    return;
                }
                if (item.qty > item.oldQty) {
                    item.qtyMaxErr = true;
                    return;
                }

                if (item.qty > 9999999.999) {
                    item.qty = 9999999.999;
                }
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            };

            EventBus.Subscribe("onMaterialChange", calcOrderTotalValue);

            function calcOrderTotalValue() {
                // 接收单位是铲运的时候 零件明细没有选择价格方案 将成交单价滞空
                if(window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId)){
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                    item.settlementPrice = item.priceSchemeName ? item.settlementPrice : 0
                    item.applyTotalPrice = item.settlementPrice == 0? 0: item.applyTotalPrice
                    });
                }
                $scope.orderObj.totalValue = 0;
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    $scope.orderObj.totalValue += (+item.applyTotalPrice || 0);
                });
                $scope.orderObj.totalValue = $filter("decimalCover")($scope.orderObj.totalValue, 2);
                console.log("xxxx")
            }

            $scope.countNetPriceTotal = function (item) {
                if (item.netPrice > 9999999.999) {
                    item.netPrice = 9999999.999;
                }
            };

            $scope.countPriceTotal = function (item) {
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.settlementPrice, item.qty), 2);
                var totalValue = 0;
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    totalValue += +item.applyTotalPrice;
                });
                $scope.orderObj.totalValue = totalValue;
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/purchaseRequest/remove";
                    var param = {};
                    param.billId = item.billId;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];

                // 申请单位默认
                $scope.orderObj.purchaseOrgName = $scope.curOrg.companyName;

                // 申请时间默认
                $scope.orderObj.createDate = new Date();

                // 收货人、手机号、收货地址默认
                setDefaultReceiver($scope.curUser.name);

                // 订单类型默认
                if ($scope.isWJ) {
                    $scope.orderObj.purchaseOrdType = 'U04';
                    $scope.orderObj.purchaseOrdTypeDesc = '分子公司备件自采订单';
                } else {
                    $scope.orderObj.purchaseOrdType = 'NB';
                    $scope.orderObj.purchaseOrdTypeDesc = '一般采购';
                }

                // 采购组默认
                $scope.orderObj.purchaseGroup = $scope.curUser.purchaseGroup;
                // 库区编码默认
                $scope.orderObj.sapInArea = $scope.isWJ ? '9000' : '';

                $scope.changeTab(2);
            };

            $scope.changeMaterialsType = function() {
                $scope.orderObj.materialsList = [];
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    if (!$scope.orderObj.supplierOrgName) {
                        ybWidget.ShowToaster('error', '请选择接收单位');
                        return;
                    }
                    if ($scope.orderObj.isDirectCast == 1 && !$scope.orderObj.soldOrgName) {
                        ybWidget.ShowToaster('error', '请选择供货商');
                        return;
                    }

                    /* if ($scope.isSupplierWj && !$scope.orderObj.materialsType) {
                        ybWidget.ShowToaster('error', '请选择零件类型');
                        return;
                    } */

                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };
            $scope.importMateriel = function () {
                if (!$scope.orderObj.supplierOrgName) {
                    ybWidget.ShowToaster('error', '请选择接收单位');
                    return;
                }
                if ($scope.orderObj.isDirectCast && !$scope.orderObj.soldOrgId) {
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }

                /* if ($scope.isSupplierWj && !$scope.orderObj.materialsType) {
                    ybWidget.ShowToaster('error', '请选择零件类型');
                    return;
                } */

                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/download",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importFilter",
                    importErrorUrl: "",
                    orgId: $scope.orderObj.supplierOrgId,
                    soldOrgId: $scope.orderObj.soldOrgId,
                    isDirectCast: $scope.orderObj.isDirectCast,
                    supplierCode: $scope.orderObj.supplierCode,
                    billId:  $scope.orderObj.billId,
                    jckPriceFlag: $scope.orderObj.jckPriceFlag,
                    otherParams: {
                        'x-materialsType': $scope.orderObj.materialsType
                    }
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                        item.totalOuter = item?.outWarehouseVO?.totalOuter;
                        item.totalInner = item?.outWarehouseVO?.innerWarehouse;
                    });
                    $scope.orderObj.materialsList = [];
                    $scope.orderObj.materialsList = angular.copy(data);
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.qtyFormatErr = false;
                        if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                            item.qtyFormatErr = true;
                        }
                        if($scope.orderObj.supplierType == "ZX"){
                            angular.forEach(item.marketingActivityPriceVOList,function(priceItem){
                                if(priceItem.name == '经销商价'){
                                    item.priceSchemeName = '经销商价';
                                    item.priceSchemeId = priceItem.activityId;
                                    item.settlementPrice = priceItem.price;
                                }
                            })
                        }
                    });
                });
            };

            $scope.importReplaceMateriel = function () {
                if (!$scope.orderObj.supplierOrgName) {
                    ybWidget.ShowToaster('error', '请选择接收单位');
                    return;
                }
                if ($scope.orderObj.isDirectCast && !$scope.orderObj.soldOrgId) {
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }
                var param = {
                    name: "替换零件",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/downloadReplaceMaterialTemp",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importReplaceMaterial",
                    importErrorUrl: "",
                    orgId: $scope.orderObj.supplierOrgId,
                    soldOrgId: $scope.orderObj.soldOrgId,
                    isDirectCast: $scope.orderObj.isDirectCast,
                    supplierCode: $scope.orderObj.supplierCode,
                    billId : $scope.orderObj.billId,
                    jckPriceFlag: $scope.orderObj.jckPriceFlag
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.materialsList = [];
                    $scope.orderObj.materialsList = angular.copy(data);
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.qtyFormatErr = false;
                        if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                            item.qtyFormatErr = true;
                        }
                    });
                });
            };

            $scope.validateMachineModel = function (item) {
                if ($scope.isJCHK && !item.machineModel) {
                    item.machineModelErr = true;
                    item.showValideErr = true;
                } else {
                    item.machineModelErr = false;
                }
                return !item.machineModelErr;
            };

            $scope.showQtyTip = function (item) {
                if (!!item.machineModelErr) {
                    item.showValideErr = true;
                }
            };

            $scope.hideQtyTip = function (item) {
                item.showValideErr = false;
            };
            // 判断数组中的值是否都相等
            $scope.isAllEqual = function (array) {
                if (array.length > 0) {
                    return !array.some(function (value, index) {
                        return value !== array[0];
                    });
                } else {
                    return true;
                }
            };

            // 校验所选零件是否属于 客户指定供方和产品
            function checkMaterial() {
                var param = {
                    materialNos: $scope.orderObj.materialsList.map(m => m.materialsNo),
                    purchaseOrgId: $scope.orderObj.supplierOrgId
                };
                return ybHttp.Post("device", "/purchaseRequest/vendorSuppliedProductVerify", param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return [];
                    }
                    return resp.value || []
                }, function() {
                    return [];
                })
            }

            $scope.clickValue = false;
            $scope.saveData = async function (type, invalid, isPlan) {
                if (!invalid) {
                    $scope.submitted = true;
                    ybWidget.ShowToaster('error', '验证不通过');
                    return;
                }

                if (!$scope.orderObj.materialsList || $scope.orderObj.materialsList.length == 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }

                var listValid = true;
                var service = "device";
                var reqUrl = "/purchaseRequest/save";
                if (type === 'submit') {
                    if (window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId)) {
                        let judgePriceFieldName = 'price';
                        if ($scope.isJCHK) {
                            // 进出口账号登录判断成交单价
                            judgePriceFieldName = 'settlementPrice';
                        }

                        // 接收单位为铲运的提交前判断单价是否有为 0的
                        const arrs = $scope.orderObj.materialsList
                        const every = arrs.some(ele=> ele[judgePriceFieldName] <=  0.00)                        
                        if (every) {
                            ybWidget.ShowToaster('error', '价格为0,联系销售');
                            return 
                        }  
                        // 判断零件属性是否一致    
                        const arr = [] 
                        $scope.orderObj.materialsList.forEach(item => {
                            arr.push(item.productPropClass)
                        })
                        if (!$scope.isAllEqual(arr)) {
                            ybWidget.ShowToaster('error', '不同属性零件，请分订单提报！');
                            return                             
                        }                                           
                    }

                    if (window.WJ_ORG_IDs.includes($scope.orderObj.supplierOrgId)) {
                        if (!$scope.orderObj.attachName) {
                            const res = await checkMaterial()
                            if (res.length > 0) {
                                ybWidget.ShowMessage('没有报告不允许提交订单！', MESG_TYPE.Error, { title: '提供指定供方及产品申请报告的提醒' })
                                return
                            }
                        }
                    }
                    reqUrl = "/purchaseRequest/submit";
                }
                
                var param = angular.copy($scope.orderObj);
                param.shippingMethod = $scope.orderObj.shippingMethod;
                param.jckPriceFlag = $scope.orderObj.jckPriceFlag
                param.seller = false;
                if (!!isPlan) {
                    reqUrl = "/purchaseRequest/saveByPlan";
                    param.billStatus = type === 'submit' ? '1' : '0';
                }
                var errMsgStr = "";
                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    if (!$scope.validateMachineModel($scope.orderObj.materialsList[i])) {
                        listValid = false;
                        errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：适用机型为空";
                        break;
                    }

                    $scope.orderObj.materialsList[i].qtyErr = false;

                    $scope.orderObj.materialsList[i].supplierErr = false;
                    $scope.orderObj.materialsList[i].supplierErrForRow = false;

                    $scope.orderObj.materialsList[i].qtyFormatErr = false;
                    $scope.orderObj.materialsList[i].dateErr = false;
                    if (!$scope.orderObj.materialsList[i].qty || parseFloat($scope.orderObj.materialsList[i].qty) <= 0) {
                        $scope.orderObj.materialsList[i].qtyErr = true;
                        listValid = false;
                        errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量不能为空和0";
                        break;
                    }

                    if ($scope.activeFlag[2] || $scope.activeFlag[8] || $scope.activeFlag[10] || $scope.activeFlag[13]) {
                        // 新增、编辑;直投新增;编辑采购申请(billStatus==2);销售创建
                    } else {
                        // 自动新增采购订单

                        if (!$scope.isWJ && !$scope.orderObj.materialsList[i].supplierCode) {
                            // 供货商必填
                            return;
                        }

                        var supplierNameHandle = $scope.orderObj.materialsList[i].supplierName?.trim();
                        if (!!supplierNameHandle) {
                            const supplierExists = $scope.orderObj.materialsList[i].purchaseInfoVOList?.some(pivf => pivf.supplierName == supplierNameHandle);
                            if (!$scope.isWJ && !supplierExists) {
                                // 采购计划里填的供货商 不在 sap采购信息接口返回的供货商列表里
                                $scope.orderObj.materialsList[i].supplierErrForRow = true; // 整行飘红
                                
                                // ybWidget.ShowToaster('error', '采购计划中供货商与xx不一致');
                                return;
                            }
                        }
                    }

                    if ($scope.orderObj.isDirectCast === 1 && $scope.orderObj.materialsList[i].isMinimumBuy && ybWidget.Remainder($scope.orderObj.materialsList[i].qty, $scope.orderObj.materialsList[i].minimumBuy) > 0) {
                        $scope.orderObj.materialsList[i].qtyFormatErr = true;
                        listValid = false;
                        errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量必须为最小购买量" + $scope.orderObj.materialsList[i].minimumBuy + "的倍数";
                        break;
                    }

                    if ($scope.activeFlag[10]) {
                        if ($scope.orderObj.materialsList[i].qty < $scope.orderObj.materialsList[i].sendQty) {
                            $scope.orderObj.materialsList[i].qtyEditErr = true;
                            listValid = false;
                            errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量不能小于已建入库单数量";
                            break;
                        }
                        if ($scope.orderObj.materialsList[i].qty > $scope.orderObj.materialsList[i].oldQty) {
                            $scope.orderObj.materialsList[i].qtyMaxErr = true;
                            listValid = false;
                            errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量不能大于原数量";
                            break;
                        }
                    }
                }
                if (!listValid) {
                    ybWidget.ShowMessage(errMsgStr, MESG_TYPE.Error);
                    return;
                }

                if ($scope.clickValue) {
                    return;
                }
                $scope.clickValue = true;

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        $scope.clickValue = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.clickValue = false;
                    $scope.changeTab(0);
                }).catch(function () {
                    $scope.clickValue = false;
                })
            };


            $scope.adjustData = function (invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }

                var listValid = true;
                var service = "device";
                var reqUrl = "/purchaseRequest/adjust";

                if (!$scope.orderObj.materialsList || $scope.orderObj.materialsList.length == 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                var param = angular.copy($scope.orderObj);
                param.shippingMethod = $scope.orderObj.shippingMethod;
                param.seller = false;

                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    $scope.orderObj.materialsList[i].qtyErr = false;
                    $scope.orderObj.materialsList[i].qtyFormatErr = false;
                    $scope.orderObj.materialsList[i].dateErr = false;
                    if (!$scope.orderObj.materialsList[i].qty || parseFloat($scope.orderObj.materialsList[i].qty) <= 0) {
                        $scope.orderObj.materialsList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                    if ($scope.orderObj.isDirectCast === 1 && $scope.orderObj.materialsList[i].isMinimumBuy && ybWidget.Remainder($scope.orderObj.materialsList[i].qty, $scope.orderObj.materialsList[i].minimumBuy) > 0) {
                        $scope.orderObj.materialsList[i].qtyFormatErr = true;
                        listValid = false;
                        break;
                    }

                }
                if (!listValid) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };


            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.selectSupplier = function () {
                var param = {
                    name: "接收单位",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {         
                    // 如果值为空或者选择相同的接收单位直接返回不做后续处理
                    if (!data.supplierOrgId || data.supplierOrgId === $scope.orderObj.supplierOrgId) {
                        return;
                    }

                    if (!$scope.isWJ) {
                        // 登录公司是非挖机，清空采购方式
                        $scope.orderObj.purchaseType = "";
                        $scope.orderObj.purchaseTypeName = "";
                        $scope.orderObj.purchaseTypeChildId = "";
                        $scope.orderObj.purchaseTypeChildName = "";
                    }

                    // 清空调度员
                    $scope.orderObj.dispatcherName = "";
                    $scope.orderObj.dispatcherId = "";

                    // 清空供货商
                    $scope.orderObj.soldOrgId = "";
                    $scope.orderObj.soldOrgName = "";

                    if(!!data.supplierOrgId && window.ZX_ORG_IDs.indexOf(data.supplierOrgId) !== -1){
                        $scope.orderObj.supplierType = "ZX";
                    }else{
                        $scope.orderObj.supplierType = "unknown";
                    }

                    $scope.orderObj.supplierCode = data.supplierCode;
                    $scope.orderObj.supplierOrgId = data.supplierOrgId;
                    $scope.orderObj.supplierOrgName = data.companyName;
                    $scope.orderObj.jckPriceFlag = data.jckPriceFlag;
                    $scope.orderObj.drawerOrgId = data.supplierOrgId;
                    $scope.orderObj.drawerOrgName = data.companyName;
                    $scope.orderObj.isPlatCompany = data.isPlatCompany;
                    $scope.isSap = data.isSap === 1;

                    $scope.isSupplierZx = judgeSupplierisZX(data.supplierOrgId);

                    if (window.WJ_ORG_IDs.includes(data.supplierOrgId)) {
                        $scope.isSupplierWj = true;

                        // 清空收货人信息（收货人、手机号、收货地址）
                        $scope.orderObj.receiverName = "";
                        $scope.orderObj.receiverTel = "";
                        $scope.orderObj.receiverAddress = "";
                    } else {
                        $scope.isSupplierWj = false;
                    }
                    // 更换接收单位的时候重新选择国家
                     $scope.orderObj.country = ''
                     // 接收单位是基础的必填的
                    if(window.JCH_ORG_IDs.includes(data.supplierOrgId)){
                        $scope.orgId = data.supplierOrgId;
                    }else{
                        $scope.orgId = "";
                    }
                    
                    clearMateriel();
                    setTimeout(() => {
                    // 铲运账号字段本身就为true
                    if (!$scope.isCHY) {
                        $timeout(function() {
                            ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'noDeliveredQty').isShow = window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId);
                            ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'lastPurchaseTime').isShow = window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId);
                            ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'thisYearPurchaseAmount').isShow = window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId);
                        })  
                    }                          
                    }, 300); 

                    getDirectLimit();
                    !!$scope.orderObj.planInfoId && $scope.agentMakeIntention({
                        id: $scope.orderObj.planInfoId,
                        dealerOrgId: data.supplierOrgId
                    }, true);

                    // 接收单位是铲运的时候隐藏单价
                    hidePrice4jchkWhenSupplierIsCY()
                })
            };

            function judgeSupplierisZX(val) {
                var zxOrgIds = window.ZX_ORG_IDs || [];
                return zxOrgIds.indexOf(val) !== -1;
            }

            $scope.clearSupplier = function () {
                $scope.isSupplierWj = false;

                // 接收单位
                $scope.orderObj.supplierOrgId = "";
                $scope.orderObj.supplierOrgName = "";

                // 出票方
                $scope.orderObj.drawerOrgId = "";
                $scope.orderObj.drawerOrgName = "";

                // 调度员
                $scope.orderObj.dispatcherName = "";
                $scope.orderObj.dispatcherId = "";

                // 供货商
                $scope.orderObj.soldOrgId = "";
                $scope.orderObj.soldOrgName = "";

                // 直投达标金额
                $scope.orderObj.directLimit = 0;

                // 零件
                clearMateriel();
            };

            $scope.selectDirectSupplier = function () {
                var param = {
                    name: "供货商",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    getDirectMaterials(data.supplierOrgId).then(function (arr) {
                        if (arr.length > 0) {
                            ybWidget.ShowMessage("该供货商下不存在此零件：" + arr.toString(), MESG_TYPE.Error);
                            return;
                        }
                        if (!!$scope.orderObj.supplierOrgId && (data.supplierOrgId !== $scope.orderObj.supplierOrgId)) {

                            // 清空调度员
                            $scope.orderObj.dispatcherName = "";
                            $scope.orderObj.dispatcherId = "";

                            // 清空采购方式
                            $scope.orderObj.purchaseType = "";
                            $scope.orderObj.purchaseTypeName = "";
                            $scope.orderObj.purchaseTypeChildId = "";
                            $scope.orderObj.purchaseTypeChildName = "";
                        }
                        $scope.orderObj.supplierOrgId = data.supplierOrgId;
                        $scope.orderObj.supplierOrgName = data.companyName;
                        $scope.orderObj.soldOrgId = data.supplierOrgId;
                        $scope.orderObj.soldOrgName = data.companyName;
                        $scope.orderObj.drawerOrgId = data.supplierOrgId;
                        $scope.orderObj.drawerOrgName = data.companyName;
                        $scope.orderObj.isPlatCompany = data.isPlatCompany;
                        $scope.isSap = data.isSap === 1;

                        if ($scope.isWJ) {
                            $scope.orderObj.purchaseOrdType = data.purchaseOrdType;
                            $scope.orderObj.purchaseOrdTypeDesc = data.purchaseOrdTypeDesc;
                        }

                        if (window.WJ_ORG_IDs.includes(data.supplierOrgId)) {
                            $scope.isSupplierWj = true;

                            // 清空收货人信息（收货人、手机号、收货地址）
                            $scope.orderObj.receiverName = "";
                            $scope.orderObj.receiverTel = "";
                            $scope.orderObj.receiverAddress = "";
                        } else {
                            $scope.isSupplierWj = false;
                        }

                        hidePrice4jchkWhenSupplierIsWJ();
                        getDirectLimit();
                    });
                })
            };

            function getDirectMaterials(suppleriOrgId) {
                var service = "device";
                var reqUrl = "/materials/purchaseMaterialsList";
                var materialsNos = getMateraisNos();
                var param = {};
                param.filters = {
                    isDirectCast: 1,
                    dealerOrgId: $scope.orderObj.deliveryOrgId,
                    supplierOrgId: suppleriOrgId,
                    materialsNos: materialsNos
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var arr = [];
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        var flag = true;
                        for (var i = 0; i < resp.value.list.length; i++) {
                            if (item.materialsNo === resp.value.list[i].materialsNo) {
                                flag = false;
                            }
                        }
                        if (flag) {
                            arr.push(item.materialsNo);
                        }
                    });
                    return arr;
                });
            }

            function getMateraisNos() {
                var materaisNos = "";
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    materaisNos = materaisNos + item.materialsNo + ",";
                });
                if (materaisNos.length > 1) {
                    materaisNos = materaisNos.substring(0, materaisNos.length - 1);
                }
                return materaisNos;
            }

            $scope.selectSold = function () {
                if (!$scope.orderObj.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请先选择接收单位');
                    return;
                }
                var param = {
                    name: "供货商",
                    type: "supplier",
                    soldOrgId: $scope.orderObj.supplierOrgId,
                    isDirect: 1,
                    purchaseOrder: true
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    // 若果返回的是控制或者选择的是相同的供货商直接返回
                    if (!data.supplierOrgId || $scope.orderObj.soldOrgId === data.supplierOrgId) {
                        return;
                    }

                    if (data.supplierOrgId == '670201763546005504') {
                        ybWidget.ShowMessage('滤芯和维修件请分开提报！', MESG_TYPE.Warn)
                    }

                    $scope.orderObj.soldOrgId = data.supplierOrgId;
                    $scope.orderObj.soldOrgName = data.shortName;

                    hidePrice4jchkWhenSupplierIsWJ();
                    clearMateriel();
                })
            };

            $scope.clearSold = function () {
                $scope.orderObj.isSpecialOrder = 0;
                $scope.orderObj.soldOrgId = "";
                $scope.orderObj.soldOrgName = "";
                clearMateriel();
            };

            $scope.selectDrawer = function () {
                var param = {
                    name: "出票方",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.drawerOrgId = data.supplierOrgId;
                    $scope.orderObj.drawerOrgName = data.companyName;
                })
            };

            $scope.clearDrawer = function () {
                $scope.orderObj.drawerOrgId = "";
                $scope.orderObj.drawerOrgName = "";
            };

            function clearMateriel() {
                if (!!$scope.orderObj.buyPlanOrder) {
                    return;
                }
                $scope.orderObj.materialsList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    EventBus.Publish("clearMaterial");
                });
            }

            $scope.selectDispatch = function () {
                if (!$scope.orderObj.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请先选择接收单位');
                    return;
                }
                var param = {
                    name: "调度员",
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.orderObj.supplierOrgId, 
                    fuzzyFlag: '1',
                    defaultRoleName: $scope.isWJ ? '' : undefined
                };
                
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.dispatcherName = data.name;
                    $scope.orderObj.dispatcherId = data.userId;
                })
            };

            $scope.selectDispatchPerson = function () {
                var param = {
                    name: "调度员",
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.orderObj.orgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.dispatcherName = data.name;
                    $scope.orderObj.dispatcherId = data.userId;
                })
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.billIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.billIds.push(item.billId);
                    }
                });
            }
            function getinfoList() {
                $scope.exportAddParam.sectionParam.infoList = [];
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    $scope.exportAddParam.sectionParam.infoList.push({
                        materialsNo: item.materialsNo,
                        materialsDes: item.materialsDes,
                        purchaseGroup: item.purchaseGroup,
                        planAmount: item.planAmount,
                        supplierName: (item.purchaseInfoVOList?.filter(item => item.supplierCode == item.supplierCode))[0]?.supplierName,
                        sapRemark: item.msg
                    });
                });
            }
            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            let countryPre = ''
            $scope.onCountryChange = function() {
                if (countryPre !== $scope.orderObj.country) {
                    // 国家改变，接收单位是挖机时，清除价格方案
                    const clientId = $scope.orderObj.supplierOrgId;
                    if (clientId && window.WJ_ORG_IDs.includes(clientId) && $scope.orderObj.materialsList.length > 0) {
                        clearAllPriceScheme();
                    }
                }
                countryPre = $scope.orderObj.country
            }

            $scope.chosePriceScheme = function (item, index) {
                var clientId = $scope.orderObj.supplierOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择接收单位');
                    return;
                }
                
                var param = {
                    schemeType: 1,
                    selectedDisabled: !$scope.isZHJCH && window.WJ_ORG_IDs.includes(clientId),
                    hideModeRateColumn: true,
                    apiObj: {
                        param: {
                            supplierOrgId: clientId,
                            materialsNo: item.materialsNo,
                            country: window.WJ_ORG_IDs.includes(clientId) ? $scope.orderObj.country : undefined
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    setPriceScheme(item, data);
                })
            };

            function setPriceScheme(item, priceScheme) {
                item.priceSchemeId = priceScheme.activityId;
                item.priceSchemeName = priceScheme.name;

                if (window.NY_ORG_IDs.includes($scope.orderObj.supplierOrgId)) {
                    // 接收单位是徐工能源时，成交单价 向上取整。
                    item.settlementPrice = String(Math.ceil(priceScheme.discountPrice||0));
                } else {
                    item.settlementPrice = $filter("decimalCover")(priceScheme.discountPrice, 2);
                }
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            }

            function clearAllPriceScheme() {
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    item.priceSchemeId = "";
                    item.priceSchemeName = "";
                    item.settlementPrice = item.price;
                    item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                });
                calcOrderTotalValue();
            }

            $scope.clearPriceScheme = function (item,type,id) {
                item.priceSchemeId = "";
                item.priceSchemeName = "";
                item.settlementPrice = item.price;
                // 当接收单位为挖机时候，删除价格方案时候价格则为0
                if (window.WJ_ORG_IDs.includes($scope.orderObj.supplierOrgId) && $scope.isJCHK) {
                    item.settlementPrice = 0
                }
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            };

            // 进出口账号登录，接收单位 选择是挖机的时候隐藏单价字段
            function hidePrice4jchkWhenSupplierIsWJ() {
                if ($scope.isJCHK) {
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'price').isShow = !window.WJ_ORG_IDs.includes($scope.orderObj.supplierOrgId);
                }
            }
            // 接收单位是铲运的时候隐藏单价
            function hidePrice4jchkWhenSupplierIsCY() {
                ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'price').isShow = !window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId);
                $scope.showAllPrice = !window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId);
            }
            function getDirectLimit() {
                var service = "device";
                var reqUrl = "/companyDealer/getDirectLimit";
                var param = {
                    orgId: $scope.orderObj.supplierOrgId
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    $scope.orderObj.directLimit = resp;
                })
            }

            $scope.switchListDatePicker = function (item) {
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    item.showDatePicker = false;
                });
                item.showDatePicker = true;
            };

            $scope.sapPost = function (item) {
                ybWidget.ShowMessage("确定要创建采购凭证吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/purchaseRequest/sapPost";
                    var param = {
                        billId: item.billId
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.sapPostBatch = function () {
                const selectedDatas = $scope.dataList.filter(df => df.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要批量创建采购凭证吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/purchaseRequest/sapPostBatch";
                    ybHttp.Post(service, reqUrl, selectedDatas.map(s => s.billId)).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.cancelApply = function (item) {
                var service = "device";
                var reqUrl = "/purchaseRequest/cancel";
                var param = {};
                param.billId = item.billId;
                ybWidget.ShowMessage("确定要撤销该采购订单吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.importAttach = function (item) {
                var param = {
                    name: "附件",
                    hideTemplate: true,
                    ignoreFormat: true,
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importAttach",
                    importErrorUrl: "",
                    billId: item.billId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            //自动新增采购订单
            $scope.autoAddApply = function () {
                //代理商和主机厂不同处理
                if (!$scope.isZHJCH) {
                    getAgentPlanDataList(1);
                    $scope.changeTab(11);
                } else {
                    getPurchaseOrderType();
                    getPlanDataList(1);
                    $scope.changeTab(4);
                }
            };

            // 代理商 自动填充采购订单信息
            $scope.agentMakeIntention = function (planInfo, getRelpaceMaterial) {
                // 获取采购计划详情信息
                getAgentPlanDetail(planInfo).then(function (res) {
                    if (!res) {
                        return;
                    }
                    if (getRelpaceMaterial) {
                        $scope.orderObj.materialsList = res.detailList || [];
                    } else {
                        // 填充新增采购申请页面的信息
                        $scope.orderObj = {
                            purchaseOrgName: res.headerInfo.deptName,
                            buyPlanOrder: res.headerInfo.planNo,
                            remark: res.headerInfo.remark,
                            isDirectCast: 0,
                            materialsList: res.detailList,
                            planInfoId: res.headerInfo.id
                        };
                    }
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.settlementPrice = item.price;
                        item.enableNum = item.stock;
                        item.qty = item.adjustQty;
                        item.applyTotalPrice = item.adjustAmount;
                        item.isChecked = false;
                    });
                    // 计算订单总额
                    calcOrderTotalValue();
                    // 跳转到新增采购申请页签
                    $scope.addApply();
                });
            }

            var materialsListBeforeFilter = []; // 记录：主机厂自动新增采购订单-选好采购计划后，页面上未进行任何操作前的原始零件信息
            $scope.makeIntention = function (planInfo, fromFlag) {
                $scope.isFromExceptionSummary = fromFlag; // 是否来自计划异常汇总页面的操作：去处理
                getPlanDataInfo(planInfo).then(function (data) {
                    if (!data) {
                        return;
                    }

                    $scope.orderObj = {
                        purchaseOrgName: data.headerInfo.deptName,
                        createDate: data.headerInfo.createDate,
                        purchaseType: data.headerInfo.typeId,
                        purchaseTypeName: data.headerInfo.typeDesc,
                        purchaseTypeChildId: data.headerInfo.purchaseTypeChildId,
                        purchaseTypeChildName: data.headerInfo.purchaseTypeChildName,
                        remark: data.headerInfo.note,
                        isDirectCast: 0,
                        materialsList: data.materialList,
                        buyPlanOrder: data.headerInfo.planOrder,
                        supplierList: data.headerInfo.supplierList,
                        isImprove: 0,
                        forward: 0,
                        orgId: data.headerInfo.orgId,
                        planCreateName: data.headerInfo.createName,
                        supplierName: data.headerInfo.supplierName
                    };

                    setDefaultReceiver(data.headerInfo.createName); // 收货人、手机号、收货地址默认

                    $scope.orderObj.purchaseGroup = $scope.isWJ ? $scope.curUser.purchaseGroup : ''; // 采购组默认
                    $scope.orderObj.sapInArea = $scope.isWJ ? '9000' : ''; // 库区编码默认

                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        // 创建字段记录总数
                        item.qtyNum = item.remainingQty
                        // 订单数量 初始化数据展示为remainingQty ， 而remainingQty 显示为 总数 -订单数量的值
                        item.qty = item.remainingQty
                        item.remainingQty =  item.qtyNum - item.qty
                        item.supplierCode =  item.materialDefuatSupplierCode ? item.materialDefuatSupplierCode : ''

                        item.settlementPrice = item.price;
                        item.applyTotalPrice = item.totalPrice;
                        item.planAmount = item.qty; 

                        if (item.orderType) {
                            item.orderTypeShow = purchaseOrderTypeList.find(pf => pf.code == item.orderType)?.name;
                        }
                    });

                    materialsListBeforeFilter = angular.copy($scope.orderObj.materialsList)
                    materialsListAfterFilterOnPurchaseGroup = null
                    materialsListAfterFilterOnOrderType = null

                    if (!$scope.isWJ) {
                        $scope.filterCondition = {
                            purchaseGroup: data.headerInfo.userPurchaseGroup,
                        };
                        $scope.filterDetail();
                    } else {
                        $scope.orderObj.purchaseGroup && filterMaterials4PurchaseGroup4auto();
                    }

                    calcOrderTotalValue();
                    $scope.changeTab(5);
                    getinfoList()
                });
            };

            var materialsListAfterFilterOnOrderType = null;
            $scope.autoPucrchaseOrderTypeChanged = function(pType) {
                if (!$scope.isWJ) {
                    return;
                }

                const mDatasTemp = materialsListAfterFilterOnPurchaseGroup || materialsListBeforeFilter;
                if (pType) {
                    $scope.orderObj.materialsList = mDatasTemp.filter(item => item.orderType == pType);
                    materialsListAfterFilterOnOrderType = angular.copy($scope.orderObj.materialsList);
                } else {
                    $scope.orderObj.materialsList = angular.copy(mDatasTemp);
                    materialsListAfterFilterOnOrderType = null;
                }
            };

            function filterMaterials4PurchaseGroup4auto() {
                const mDatasTemp = materialsListAfterFilterOnOrderType || materialsListBeforeFilter;
                $scope.orderObj.materialsList = mDatasTemp.filter(item => item.purchaseGroup == $scope.orderObj.purchaseGroup);
                materialsListAfterFilterOnPurchaseGroup = angular.copy($scope.orderObj.materialsList);
            }
            var materialsListAfterFilterOnPurchaseGroup = null;
            $scope.selectPurchaseGroup4auto = function () {
                var param = {
                    name: "采购组",
                    type: "purchaseGroup"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.purchaseGroup = data.code;

                    if ($scope.isWJ) {
                        filterMaterials4PurchaseGroup4auto();
                    }
                })
            };

            $scope.clearPurchaseGroup4auto = function () {
                $scope.orderObj.purchaseGroup = "";

                if ($scope.isWJ) {
                    const mDatasTemp = materialsListAfterFilterOnOrderType || materialsListBeforeFilter;
                    $scope.orderObj.materialsList = angular.copy(mDatasTemp);
                    materialsListAfterFilterOnPurchaseGroup = null;
                }
            };

            $scope.filterDetail = function () {
                if (!$scope.filterCondition.materialsNo && !$scope.filterCondition.purchaseGroup && !$scope.filterCondition.supplierCodeInfo) {
                    return;
                }

                var materialsList = [];
                angular.forEach(materialsListBeforeFilter, function (item) {
                    var flag = true;

                    if (!!$scope.filterCondition.materialsNo && item.materialsNo !== $scope.filterCondition.materialsNo) {
                        flag = false;
                    }

                    if (!!$scope.filterCondition.purchaseGroup && item.purchaseGroup !== $scope.filterCondition.purchaseGroup) {
                        flag = false;
                    }

                    if (!!$scope.filterCondition.supplierCodeInfo) {
                        let findRes
                        if ($scope.isWJ) {
                            const selectedSuCodes = $scope.filterCondition.supplierCodeInfo.ids || [];
                            findRes = item.purchaseInfoVOList?.find(pvf => selectedSuCodes.includes(pvf.supplierSapCode));
                        } else {
                            findRes = item.purchaseInfoVOList?.find(pvf => $scope.filterCondition.supplierCodeInfo === pvf.supplierSapCode);
                        }

                        if (!findRes) {
                            flag = false;
                        } else {
                            if (!$scope.isWJ) {
                                item.supplierCode = findRes.supplierSapCode;
                                item.supplierOrgName = findRes.supplierName;
                            }
                        }
                    }
                    if (flag) {
                        materialsList.push(item);
                    }
                });
                $scope.orderObj.materialsList = materialsList;
            };

            $scope.filterReset = function () {
                $scope.filterCondition = {};
                $scope.orderObj.materialsList = angular.copy(materialsListBeforeFilter);
            };

            $scope.selectPurchaseGroup = function () {
                var param = {
                    name: "采购组",
                    type: "purchaseGroup"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.purchaseGroup = data.code;
                })
            };

            $scope.clearPurchaseGroup = function () {
                $scope.orderObj.purchaseGroup = "";
            };

            //代理商采购计划信息
            $scope.agentPlan = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                condition: {},
                dataList: [],
                toolbarConfig: {
                    showAdvanceSearch: false,
                    showColConfig: false,
                    showMateriel: false
                },
                tableConfig: {
                    fixedWidth: 120,
                    scrollWidth: 920,
                    tableCol: [{
                            type: "",
                            name: "采购计划单号",
                            dataField: "planNo",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "采购类型",
                            dataField: "typeDesc",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: "",
                            isEN: true
                        },
                        {
                            type: "",
                            name: "制单人",
                            dataField: "createName",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "审核人",
                            dataField: "auditName",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "审核时间",
                            dataField: "auditTimeShow",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "备注",
                            dataField: "remark",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: false,
                            sortType: ""
                        },
                        {
                            type: "operate",
                            name: "操作",
                            dataField: "",
                            width: 120,
                            isShow: true,
                            isFixed: true,
                            toSort: false,
                            sortType: ""
                        }
                    ]
                },
                //搜索
                search: function (curPage) {
                    getAgentPlanDataList(curPage);
                },
                //重置搜索条件
                reset: function () {
                    $scope.agentPlan.condition = {};
                },
                //隐藏和展示高级搜索
                switchToolbar: function (toolbar) {
                    if (!!$scope.agentPlan.toolbarConfig["show" + toolbar]) {
                        $scope.agentPlan.toolbarConfig["show" + toolbar] = false;
                    } else {
                        $timeout(function () {
                            $scope.agentPlan.toolbarConfig["show" + toolbar] = true;
                        });
                    }
                },
                //设置表格列的宽度
                setFixedWidth: function () {
                    $scope.agentPlan.tbStyle = {
                        sellFixedWidth: {
                            left: $scope.selectPlan.tableConfig.fixedWidth + "px"
                        }
                    };
                },
            };

            //主机厂采购计划信息
            $scope.selectPlan = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                markInfo: {},
                condition: {
                    purchaseGroup: $scope.curUser.purchaseGroup
                },
                dataList: [],
                toolbarConfig: {
                    showAdvanceSearch: false,
                    showColConfig: false,
                    showMateriel: false
                },
                tableConfig: {
                    fixedWidth: 120,
                    scrollWidth: 920,
                    tableCol: [{
                            type: "",
                            name: "采购计划单号",
                            dataField: "planOrder",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请人",
                            dataField: "createName",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请部门",
                            dataField: "deptName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请时间",
                            dataField: "createDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "采购方式",
                            dataField: "purchaseType",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "供货商",
                            dataField: "supplierName",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "备注",
                            dataField: "note",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "审核状态",
                            dataField: "auditStatusShow",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "审核时间",
                            dataField: "auditDateShow",
                            width: 160,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "operate",
                            name: "操作",
                            dataField: "",
                            width: 120,
                            isShow: true,
                            isFixed: true,
                            toSort: false,
                            sortType: ""
                        }
                    ]
                },

                search: function (curPage) {
                    getPlanDataList(curPage);
                },
                reset: function () {
                    $scope.selectPlan.condition = {};
                },
                switchToolbar: function (toolbar) {
                    if (!!$scope.selectPlan.toolbarConfig["show" + toolbar]) {
                        $scope.selectPlan.toolbarConfig["show" + toolbar] = false;
                    } else {
                        $timeout(function () {
                            $scope.selectPlan.toolbarConfig["show" + toolbar] = true;
                        });
                    }
                },
                setFixedWidth: function () {
                    $scope.selectPlan.tbStyle = {
                        sellFixedWidth: {
                            left: $scope.selectPlan.tableConfig.fixedWidth + "px"
                        }
                    };
                },
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                selectRow: function (index) {
                    $scope.selectPlan.markInfo.cueRow = index
                },
            };

            //获取代理商审核通过的汇总采购计划列表
            function getAgentPlanDataList(pageNum) {
                var url = '/agentPlan/list4PurchaseRequest';
                var service = "device";
                //遍历搜索条件对象里的空值并删除  不然搜索不出数据
                Object.keys($scope.agentPlan.condition).forEach(function (key) {
                    if (!$scope.agentPlan.condition[key]) delete $scope.agentPlan.condition[key];
                });
                var param = {
                    pageSize: $scope.agentPlan.pageInfo.pageSize,
                    pageNum: pageNum || $scope.agentPlan.pageInfo.pageSize,
                    filters: $scope.agentPlan.condition,
                    orderType: 1
                };
                ybHttp.Post(service, url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(res.value.pageInfoList, function (item) {
                        item.auditTimeShow = $filter("YbDate")(item.auditTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.agentPlan.pageInfo.totalRows = res.value.pageInfo.total;
                    $scope.agentPlan.pageInfo.totalPages = res.value.pageInfo.pages;
                    $scope.agentPlan.dataList = res.value.pageInfoList;
                })
            }

            function getPlanDataList(curPage) {
                var service = "device";
                var reqUrl = "/buyPlan/autoCreate/list";
                var param = {};
                param.pageSize = $scope.selectPlan.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.selectPlan.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.selectPlan.pageInfo.curPage;
                param.filters = angular.copy($scope.selectPlan.condition);
                param.filters.auditStatus = 1;
                param.filters.notComplete = 1;
                param.filters.finishStates = ['0', '1'];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditStatusShow = $filter("ProgressStatus")(item.auditStatus, "audit");
                        item.purchaseType = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.selectPlan.pageInfo.totalRows = resp.value.total;
                    $scope.selectPlan.pageInfo.totalPages = resp.value.pages;
                    $scope.selectPlan.dataList = resp.value.list;
                });
            }

            function getPlanDataInfo(planInfo) {
                var param = {
                    id: planInfo.id
                };
                const url = !$scope.isFromExceptionSummary ? '/buyPlan/itemForPurchase' : '/buyPlan/itemForAnomalyBuyPlanPurchase';
                return ybHttp.Get('device', url, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            //获取代理商采购计划详情
            function getAgentPlanDetail(planInfo) {
                var param = {
                    planId: planInfo.id,
                    dealerOrgId: planInfo.dealerOrgId
                };
                return ybHttp.Get('device', '/agentPlan/select4PurchaseOrder', param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    return res.value;
                });
            }

            $scope.sapAddObj = {};
            $scope.sapAddSubmitted = false;
            $scope.sapAdd = function () {
                $scope.sapAddSubmitted = false;
                $scope.sapAddObj = {};
                $scope.changeTab(6);
            };

            $scope.handleSapBillNoBlur = function(e) {
                $scope.sapAddObj.sapBillNo = UserContextService.MultiInput(e.target.value);
            };

            $scope.saveSapAddData = function (invalid) {
                if (!invalid) {
                    $scope.sapAddSubmitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/purchaseRequest/sapAdd";
                var param = angular.copy($scope.sapAddObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.changeTab(0);
                    var errorList = resp.value || [];
                    if (errorList.length > 0) {
                        ybWidget.ShowMessage(errorList.join("<br />"), MESG_TYPE.Error, {
                            isHtml: true
                        });
                    } else {
                        ybWidget.ShowToaster('success', '操作成功');
                    }
                });
            };

            /*直投采购计划*/
            $scope.directAddApply = function () {
                getDircectPurchasePlanDataList(1);
                $scope.changeTab(7);
            };
            $scope.directPurchasePlan = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                markInfo: {},
                condition: {},
                dataList: [],
                toolbarConfig: {
                    showAdvanceSearch: false,
                    showColConfig: false,
                    showMateriel: false
                },
                tableConfig: {
                    fixedWidth: 120,
                    scrollWidth: 920,
                    tableCol: [{
                            type: "",
                            name: "采购订单号",
                            dataField: "billNo",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请单位",
                            dataField: "purchaseOrgName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "供货商",
                            dataField: "soldOrgName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "直投达标金额",
                            dataField: "directLimit",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "备注",
                            dataField: "remark",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请时间",
                            dataField: "createDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "operate",
                            name: "操作",
                            dataField: "",
                            width: 120,
                            isShow: true,
                            isFixed: true,
                            toSort: false,
                            sortType: ""
                        }
                    ]
                },

                search: function (curPage) {
                    getDircectPurchasePlanDataList(curPage);
                },
                reset: function () {
                    $scope.directPurchasePlan.condition = {};
                },
                switchToolbar: function (toolbar) {
                    if (!!$scope.directPurchasePlan.toolbarConfig["show" + toolbar]) {
                        $scope.directPurchasePlan.toolbarConfig["show" + toolbar] = false;
                    } else {
                        $timeout(function () {
                            $scope.directPurchasePlan.toolbarConfig["show" + toolbar] = true;
                        });
                    }
                },
                setFixedWidth: function () {
                    $scope.directPurchasePlan.tbStyle = {
                        sellFixedWidth: {
                            left: $scope.directPurchasePlan.tableConfig.fixedWidth + "px"
                        }
                    };
                },
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                selectRow: function (index) {
                    $scope.directPurchasePlan.markInfo.cueRow = index
                }
            };

            function getDircectPurchasePlanDataList(curPage) {
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                var param = {};
                param.pageSize = $scope.directPurchasePlan.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.directPurchasePlan.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.directPurchasePlan.pageInfo.curPage;
                param.filters = angular.copy($scope.directPurchasePlan.condition);
                param.filters.seller = true;
                param.filters.billStatus = "2";
                param.filters.isDirectAdd = 0;
                param.filters.isDirectCast = 1;
                param.filters.onlyDirect = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.directPurchasePlan.pageInfo.totalRows = resp.value.total;
                    $scope.directPurchasePlan.pageInfo.totalPages = resp.value.pages;
                    $scope.directPurchasePlan.dataList = resp.value.list;
                });
            }

            function getDircectPurchasePlanDataInfo(planInfo) {
                var param = {
                    billId: planInfo.billId,
                    isDirect: 1
                };
                return ybHttp.Get('device', '/purchaseRequest/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            $scope.createDirectPurchaseOrder = function (planInfo) {
                getDircectPurchasePlanDataInfo(planInfo).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = angular.copy(data);
                    $scope.orderObj.purchaseOrgId = data.supplierOrgId;
                    $scope.orderObj.purchaseOrgName = data.supplierOrgName;
                    $scope.orderObj.supplierOrgId = $scope.orderObj.soldOrgId;
                    $scope.orderObj.supplierOrgName = $scope.orderObj.soldOrgName;
                    $scope.orderObj.deliveryOrgId = data.purchaseOrgId;
                    $scope.orderObj.deliveryOrgName = data.purchaseOrgName;
                    $scope.orderObj.directSourceOrder = data.billNo;
                    $scope.orderObj.directSourceId = data.billId;
                    $scope.orderObj.dispatcherName = '';
                    $scope.orderObj.dispatcherId = '';
                    $scope.orderObj.billId = '';
                    $scope.orderObj.billNo = '';

                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.deliveryDateStr = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd');
                    });
                    $scope.changeTab(8);

                    if ($scope.isWJ) {
                        // 1,挖机的订单类型：根据供货商自动带出
                        // 2,挖机的采购组：默认F11
                        $scope.orderObj.purchaseGroup = 'F11'
                    } else {
                        $scope.orderObj.purchaseOrdType = 'NB';
                        $scope.orderObj.purchaseOrdTypeDesc = '一般采购';
                    }
                });
            };

            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("onMaterialChange", calcOrderTotalValue);
            });

            $scope.barCodePage = {
                dataList: [],
                detailInfo: {},
                packList: [],
                currentMaterial: {},
                markInfo: {},
                tableConfig: {
                    scrollWidth: 720,
                    tableCol: [{
                            type: "",
                            name: "打印标志",
                            dataField: "stateName",
                            width: 90
                        },
                        {
                            type: "",
                            name: "零件编号",
                            dataField: "materialsNo",
                            width: 120
                        },
                        {
                            type: "",
                            name: "零件中文名",
                            dataField: "materialsDes",
                            width: 120
                        },
                        {
                            type: "",
                            name: "数量",
                            dataField: "qty",
                            width: 80
                        },
                        {
                            type: "",
                            name: "未打数量",
                            dataField: "restAmount",
                            width: 100
                        },
                        {
                            type: "",
                            name: "操作标志",
                            dataField: "statusName",
                            width: 90
                        }
                    ]
                },
                countPack: function () {
                    $scope.barCodePage.detailInfo.packNum = parseFloat($scope.barCodePage.detailInfo.packNum);
                    if ($scope.barCodePage.detailInfo.totalQty > $scope.barCodePage.currentMaterial.restAmount) {
                        $scope.barCodePage.detailInfo.totalQty = $scope.barCodePage.currentMaterial.restAmount;
                    }
                    setEachPack();
                },
                setPackNum: function () {
                    $scope.barCodePage.detailInfo.packNum = parseInt($scope.barCodePage.detailInfo.packNum);
                    setEachPack();
                },
                selectRow: function (index) {
                    if ($scope.barCodePage.dataList[index].printState == 2) {
                        ybWidget.ShowToaster('error', '请选择条码生成未完成的零件');
                        return;
                    }
                    $scope.barCodePage.markInfo.cueRow = index;
                    $scope.barCodePage.currentMaterial = $scope.barCodePage.dataList[index];
                    $scope.barCodePage.detailInfo.totalQty = angular.copy($scope.barCodePage.currentMaterial.restAmount);
                    $scope.barCodePage.detailInfo.packNum = 1;
                    $scope.barCodePage.packList = [{
                        currentQty: $scope.barCodePage.currentMaterial.restAmount,
                        vinid: ''
                    }];
                }
            };
            var currentBillItem = null;
            $scope.createBarcode = function (item) { // 生成条码
                getDetail(item).then(function (billDetail) {
                    if (!billDetail) {
                        return;
                    }
                    currentBillItem = item;
                    $scope.barCodePage.detailInfo = {};
                    $scope.barCodePage.markInfo.cueRow = null;
                    angular.forEach(billDetail.materialsList, function (item) {
                        item.stateName = $filter('printState')(item.printState);
                        item.statusName = $filter('allotState')(item.printState);
                        item.restAmount = item.qty - (item.printNum || 0);
                    });
                    $scope.barCodePage.dataList = billDetail.materialsList;
                    $scope.changeTab(9);
                });
            };
            $scope.createMaterialBarcode = function () {
                if (!$scope.barCodePage.currentMaterial.materialsNo) {
                    ybWidget.ShowMessage("没有可打印的条码", MESG_TYPE.Error);
                    return;
                }
                var service = "device";
                var reqUrl = "/barcode/singlePurchasePrint";
                var param = {};
                param.billNo = currentBillItem.billNo;
                param.billId = currentBillItem.billId;
                param.rowNo = currentBillItem.rowNo;
                param.materialsNo = $scope.barCodePage.currentMaterial.materialsNo;
                param.materialsDes = $scope.barCodePage.currentMaterial.materialsDes;
                param.totalQty = $scope.barCodePage.detailInfo.totalQty;
                param.detailList = [];
                angular.forEach($scope.barCodePage.packList, function (item) {
                    var detailItem = {};
                    detailItem.barcodeDesc = $scope.barCodePage.detailInfo.barcodeDesc;
                    detailItem.model = $scope.barCodePage.detailInfo.model;
                    detailItem.orawyd = $scope.barCodePage.detailInfo.orawyd;
                    detailItem.currentQty = item.currentQty;
                    detailItem.vinid = item.vinid;
                    param.detailList.push(detailItem);
                });
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.createBarcode(currentBillItem); // 刷新当前页面数据
                });
            };

            function setEachPack() {
                $scope.barCodePage.packList = [];
                var eachPackNum = Math.floor($scope.barCodePage.detailInfo.totalQty / $scope.barCodePage.detailInfo.packNum);
                for (var i = 0; i < $scope.barCodePage.detailInfo.packNum; i++) {
                    var objData = {
                        currentQty: eachPackNum,
                        vinid: ''
                    };
                    if (i == $scope.barCodePage.detailInfo.packNum - 1) {
                        objData.currentQty = Number((objData.currentQty + $scope.barCodePage.detailInfo.totalQty % $scope.barCodePage.detailInfo.packNum).toFixed(3));
                    }
                    $scope.barCodePage.packList.push(objData);

                }
            }

            $scope.pucrchaseOrderTypeChanged = function (purchaseOrderType) {

                if (purchaseOrderType !== 'Z04') { // 不是集团采购
                    clearAllMaterialList();
                    return;
                }
                var param = {
                    filters: {
                        supplierCode: "4040"
                    },
                    pageNum: 1,
                    pageSize: 0

                };
                ybHttp.Post('device', '/companySupplier/list', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (resp.value.list.length > 0) {
                        $scope.orderObj.supplierOrgName = resp.value.list[0].companyName;
                        $scope.orderObj.supplierOrgId = resp.value.list[0].supplierOrgId;
                        $scope.orderObj.drawerOrgName = $scope.orderObj.supplierOrgName;
                        $scope.orderObj.drawerOrgId = $scope.orderObj.supplierOrgId;
                    }
                });
                clearAllMaterialList();

            };

            function clearAllMaterialList() {
                for (var i = $scope.orderObj.materialsList.length - 1; i >= 0; i--) {
                    $scope.orderObj.materialsList.splice(i, 1);
                }
                if ($scope.orderObj.materialsList.length === 0) {
                    $scope.markInfo.allCheckedMaterial = false;
                }
                EventBus.Publish("setMaterial");
            }

            $scope.searchAddress = function (deliveryName) {
                ybWidget.SelectDeliveryAddress({
                    deliveryName: deliveryName,
                    clientReceiveInfo: $scope.isSupplierWj,
                    supplierOrgId: $scope.orderObj.supplierOrgId
                }).then(function (data) {
                    $scope.orderObj.receiverName = data.receiverName;
                    $scope.orderObj.receiverTel = data.receiverTel;
                    $scope.orderObj.receiverAddress = data.receiverAddress;
                    $scope.orderObj.addressCode = data.addressCode;
                });
            };

            function setDefaultReceiver(curUserName) {
                var service = 'device';
                var reqUrl = '/companyAddress/receiverMatching';
                ybHttp.Get(service, reqUrl, {}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (resp.value && resp.value.length > 0) {
                        var defaultReceiver = resp.value.find(function(o) { return o.receiverName == curUserName })
                        $scope.orderObj.receiverName = curUserName;
                        if (defaultReceiver) {
                            $scope.orderObj.receiverTel = defaultReceiver.receiverTel;
                            $scope.orderObj.receiverAddress = defaultReceiver.receiverAddress;
                            $scope.orderObj.addressCode = defaultReceiver.addressCode;
                        }
                    }
                });
            }

            $scope.changeSupplierCode = function() {
                getinfoList()
            }

            $scope.go2logistics = function (item) {
                EventBus.Publish('go2otherMenuPage', {
                    name: "app.logistics.handoverBill",
                    params: {
                        orderNo: item.billNo
                    }
                });
            };

            $scope.addApplyFromSalesOrder = function () {
                $scope.orderCondition.buyerName = $scope.curUser.name;
                getOrderDataList();
                $scope.changeTab(13);
            };

            $scope.curStep = 0;

            $scope.orderCondition = {
                status: 1,
                notDirect: 1,
                deliveryListFlag: 1,
                purchaseListFlag: 1,
            };

            $scope.orderPageInfo = {
                totalRows: 0,
                totalPages: 1,
                pageSize: 10,
                curPage: 1
            };

            $scope.orderSearch = function () {
                getOrderDataList();
            };

            function getOrderDataList(curPage) {
                var service = "device";
                var reqUrl = "/saleIntention/list";
                var param = {};
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                var param = {
                    pageSize:  $scope.orderPageInfo.pageSize,
                    pageNum:  $scope.orderPageInfo.curPage,
                    filters: angular.copy($scope.orderCondition)
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            }

            $scope.orderSelectSingle = function ({ id:orderId, country }) {
                if ($scope.isJCHK && !$scope.countries.find(o => o.name == country)) {
                    ybWidget.ShowMessage('没有国家和地区权限!', MESG_TYPE.Error)
                    return
                }

                ybHttp.Get('device', '/saleIntention/purchaseCreateQuerySaleIntention', { id: orderId }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    const { remark, deliverTypeName, sendTypeChildName } = resp.value?.headerInfo || {};
                    $scope.orderObj.remark = remark;
                    $scope.orderObj.saleSendType = `${deliverTypeName || ''}-${sendTypeChildName || ''}`;

                    $scope.orderObj.purchaseOrgName = $scope.curOrg.companyName; // 申请单位默认

                    $scope.orderObj.createDate = new Date(); // 申请时间默认

                    setDefaultReceiver($scope.curUser.name); // 收货人、手机号、收货地址默认

                    $scope.orderObj.country = resp.value.headerInfo.country;

                    $scope.orderObj.supplierOrgId = resp.value.headerInfo.targetOrgId;

                    $scope.isSupplierZx = judgeSupplierisZX($scope.orderObj.supplierOrgId);

                    $scope.orderObj.supplierOrgName = resp.value.headerInfo.targetOrgName;
                    $scope.orderObj.forward = resp.value.headerInfo.forward;
                    $scope.orderObj.forwardProtocolNo = resp.value.headerInfo.forwardProtocolNo;
                    $scope.orderObj.purchaseContractNo = resp.value.headerInfo.saleNo;

                    var deliveryDateT = resp.value.headerInfo.deliveryDate;
                    $scope.orderObj.deliveryDate = deliveryDateT ? new Date(deliveryDateT) : null;

                    angular.forEach(resp.value.materialList,function(item) {
                        item.settlementPrice = item.unitPriceAfterAdjust;
                        if(!!item.marketingActivityPriceVOList){
                            angular.forEach(item.marketingActivityPriceVOList,function(itemPriceVOList){
                                if(itemPriceVOList.activityId == item.priceSchemeId && !!itemPriceVOList.discountPrice){
                                    item.settlementPrice = $filter("decimalCover")(itemPriceVOList.discountPrice, 2);
                                }
                            })
                        }
                        if(!item.settlementPrice){
                            item.settlementPrice = item.price;
                        }
                        item.qty = item.amountAfterAdjust;
                        item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                    })

                    $scope.orderObj.materialsList = resp.value.materialList;

                    calcOrderTotalValue();

                    $scope.curStep = 1;
                });
            };

            $scope.$watch('orderObj.supplierOrgId', function(newVal) {
                // 判断零件是否进出口 0 否 (可选)1 是(不可选) showPricePlan
                if (window.JCHK_ORG_IDs.includes($scope.orderObj.supplierOrgId)){
                    if ($scope.orderObj.jckPriceFlag == 1) {    
                        $scope.showPricePlan = false
                    }else if($scope.orderObj.jckPriceFlag == 0){  
                        $scope.showPricePlan = true
                    }
                }else {
                    $scope.showPricePlan = true
                }
            })    

            function waibuStock(item) {
                const param = {
                    title: '外部库存',
                    fields: [
                        { name: '仓库编号', dataField: 'warehouse', width: '30%' },
                        { name: '仓库描述', dataField: 'warehouseName', width: '40%' },
                        { name: '库存', dataField: 'num', width: '30%' }
                    ],
                    data: item?.outWarehouseVO?.outerWarehouseItems || []
                }
                ybWidget.DatasShow(param);
            }

            function qitaStock(item) {
                ybWidget.DataSelector({
                    title: '其他经销商库存',
                    url: '/warehouseInventory/wjDealerList',
                    otherParams: {
                        materialNo: item.materialsNo,
                        dealerOrgId: $scope.curOrgId,
                        supplierOrgId: $scope.orderObj.supplierOrgId
                    },
                    fields: [
                        {
                            name: '经销商名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '可用库存',
                            dataField: 'enableNum',
                            width: "40%"
                        },
                    ],
                    isOnlyShow: true,
                })
            }

            function handleAttachFiles(attachNameStr) {
                if (!attachNameStr) {
                    return [];
                }
                return attachNameStr.split(',').map(an => {
                    const fName = an.split('/').pop()
                    return {
                        fileUrl: an,
                        name: fName,
                        filename: fName,
                        hasUpload: true,
                    }
                })
            }

            $scope.uploadDetailAttach = function(item) {
                const param = {
                    ImgTypes: 'jpg',
                    FileTypes: 'pdf,doc,docx,xls,xlsx',
                    ImgSize: 5,
                    FileSize: 5,
                    maxFileCount: 1,
                    urlType: 'minio',
                    mnDir: 'pms-jituan/',
                    fileList: item.attachFiles || handleAttachFiles(item.attachPath)
                }
                ybWidget.FileUploader(param).then(res => {
                    const fileListTemp  = res.fileList || [];
                    item.attachFiles = fileListTemp;
                    item.attachPath = fileListTemp.filter(item => !!item.fileUrl).map(an => an.fileUrl).join(',');
                })
            };

            $scope.downloadDetailAttach = function(item) {
                window.location.href = ybHttp.RequestUrl("device", "/purchaseRequest/downloadDetailAttach") + '?x-billId=' + item.billId + '&materialsNo=' + item.materialsNo;
            };

            var purchaseOrderTypeList = [];
            function getPurchaseOrderType() {
                if (purchaseOrderTypeList.length > 0) {
                    return;
                }
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "CGDDLX"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    purchaseOrderTypeList = resp.value;
                })
            }

            $scope.scheduleExceptionInfo = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                dataList: [],
                condition: {},
                search: function (curPage) {
                    getScheduleExceptionDataList(curPage);
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewDetail":
                            var param = {
                                id: item.id
                            };
                            ybHttp.Get('device', '/buyPlan/itemAnomalyPlan', param).then(function (resp) {
                                if (resp.code !== 0) {
                                    ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                    return;
                                }
                                if (resp.value && resp.value.materialList && resp.value.materialList.length > 0) {
                                    angular.forEach(resp.value.materialList, function(item){
                                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd');
                                        item.stockAddStateShow = $filter("ProgressStatus")(item.stockAddState, 'stockAddStatus');
                                        item.isGenerateShow = $filter("ProgressStatus")(item.isGenerate, 'generateState');
                                        item.stockAddRejectTimeShow = $filter("YbDate")(item.stockAddRejectTime, 'yyyy-MM-dd');
                                    })
                                }
                                $scope.buyPlanInfo = resp.value || {};
                                $scope.changeTab(15);
                            });
                            break;
                        default:
                            break;
                    }
                },
                tbStyle: {
                    scrollLeft: { left: 80 + "px" },
                },
                tableConfig: {
                    fixedWidth: 80,
                    scrollWidth: 1500,
                    tableCol: [
                        {
                            type: "operate",
                            name: "操作",
                            width: 80,
                            isShow: true,
                            isFixed: true,
                        },
                        {
                            name: "采购计划单号",
                            dataField: "planOrder",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            clickFn: "viewDetail",
                        },
                        {
                            name: "申请人",
                            dataField: "createName",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "申请部门",
                            dataField: "deptName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "申请时间",
                            dataField: "createDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "采购方式",
                            dataField: "purchaseType",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "备注",
                            dataField: "note",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核人",
                            dataField: "auditName",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核时间",
                            dataField: "auditDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核状态",
                            dataField: "auditStatusShow",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核意见",
                            dataField: "auditNote",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "创建采购单状态",
                            dataField: "sendStatusShow",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                    ]
                },
                tableConfigDetail: {
                    scrollWidth: 1100,
                    tableCol: [
                        {
                            name: "零件编号",
                            width: 150,
                            dataField: "materialsNo",
                            needInput: false
                        },
                        {
                            name: "零件中文名",
                            width: 150,
                            dataField: "materialsDes",
                            needInput: false
                        },
                        {
                            name: "零件分类",
                            width: 120,
                            dataField: "materialsType",
                            needInput: false
                        },
                        {
                            name: "零件单位",
                            width: 120,
                            dataField: "unit",
                            needInput: false
                        },
                        {
                            name: "采购组",
                            width: 120,
                            dataField: "purchaseGroup",
                            needInput: false
                        },
                        {
                            name: "供货商",
                            width: 100,
                            dataField: "supplierName",
                            needInput: true,
                            inputType: "supplierName"
                        },
                        {
                            name: "替换零件编号",
                            width: 120,
                            dataField: "replaceMaterialsNo",
                            needInput: false
                        },
                        {
                            name: "替换零件中文名",
                            width: 120,
                            dataField: "replaceMaterialsDes",
                            needInput: false
                        },
                        {
                            name: "单价(￥)",
                            width: 100,
                            dataField: "price",
                            needInput: false,
                            inputType: "price"
                        },
                        {
                            name: "数量",
                            width: 100,
                            dataField: "qty",
                            needInput: true,
                            inputType: "qty"
                        },
                        {
                            name: "交货日期",
                            width: 140,
                            dataField: "deliveryDateShow",
                        },
                        {
                            name: "备注",
                            width: 100,
                            dataField: "remark",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "是否创建采购单",
                            width: 120,
                            dataField: "isGenerateShow",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "审批状态",
                            width: 120,
                            dataField: "stockAddStateShow",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "驳回原因",
                            width: 120,
                            dataField: "stockAppRemark",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "驳回时间",
                            width: 140,
                            dataField: "stockAddRejectTimeShow",
                            needInput: false,
                            inputType: ""
                        },
                    ]
                }
            };

            function getScheduleExceptionDataList(curPage) {
                var service = "device";
                var reqUrl = "/buyPlan/anomalys";
                
                if (!!curPage) {
                    $scope.scheduleExceptionInfo.pageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.scheduleExceptionInfo.pageInfo.pageSize,
                    pageNum: $scope.scheduleExceptionInfo.pageInfo.curPage,
                    filters: angular.copy($scope.scheduleExceptionInfo.condition)
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditStatusShow = $filter("ProgressStatus")(item.auditStatus, "audit");
                        item.sendStatusShow = $filter("ProgressStatus")(item.sendStatus, "sendState");
                        item.purchaseType = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                    });
                    $scope.scheduleExceptionInfo.pageInfo.totalRows = resp.value.total;
                    $scope.scheduleExceptionInfo.pageInfo.totalPages = resp.value.pages;
                    $scope.scheduleExceptionInfo.dataList = resp.value.list;
                });
            }
            $scope.scheduleExceptionSummary = function () {
                getPurchaseOrderType();
                $scope.scheduleExceptionInfo.pageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                }
                $scope.scheduleExceptionInfo.dataList = [];
                $scope.scheduleExceptionInfo.condition = {};
                getScheduleExceptionDataList(1).then(() => {
                    $scope.changeTab(14);
                })
            };

            // 把导入的供货商代码、创建订单数量、备注 填充到 零件列表中
            function handleObjAssign(targetItem, valObj) {
                if (targetItem) {
                    targetItem.supplierCode = valObj.supplierCode;
                    targetItem.qty = valObj.qty;
                    targetItem.remark = valObj.remark;
                }
            }
            $scope.importMateriel4Override = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    downloadMethod: 'get',
                    templateReqUrl: "/purchaseRequest/materialOverrideTmpDownload",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/materialImportOverride",
                    importErrorUrl: "",
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        // mFilterRes、mFilterOnOrderTypeRes、mFilterOnPurchaseGroupRes:从过滤操作中 保存的原始零件数据中查找到的零件；
                        // mCurRes:从当前页面 最终显示的零件数据中查找到的零件；

                        const mFilterRes = materialsListBeforeFilter?.find(m => m.materialsNo == item.materialsNo);
                        const mFilterOnOrderTypeRes = materialsListAfterFilterOnOrderType?.find(m => m.materialsNo == item.materialsNo);
                        const mFilterOnPurchaseGroupRes = materialsListAfterFilterOnPurchaseGroup?.find(m => m.materialsNo == item.materialsNo);

                        if (mFilterRes) { // 导入的零件在本采购计划零件明细中
                            handleObjAssign(mFilterRes, item);

                            if (mFilterOnOrderTypeRes) {
                                handleObjAssign(mFilterOnOrderTypeRes, item);
                            }
                            if (mFilterOnPurchaseGroupRes) {
                                handleObjAssign(mFilterOnPurchaseGroupRes, item);
                            }

                            const mCurRes = $scope.orderObj.materialsList.find(m => m.materialsNo == item.materialsNo);
                            if (mCurRes) { // // 导入的零件在 当前页面显示的零件明细中
                                handleObjAssign(mCurRes, item);
                            }
                        }
                    });
                });
            };


            $scope.dscRejectInfo = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                dataList: [],
                condition: {},
                search: function (curPage) {
                    getDscRejectDataList(curPage);
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewDetail":
                            break;
                        default:
                            break;
                    }
                },
                tbStyle: {
                    scrollLeft: { left: 80 + "px" },
                },
                tableConfig: {
                    fixedWidth: 80,
                    scrollWidth: 1500,
                    tableCol: [
                        {
                            type: "operate",
                            name: "操作",
                            width: 80,
                            isShow: true,
                            isFixed: true,
                        },
                        {
                            name: "供货商代码",
                            dataField: "supplierNum",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "供货商名称",
                            dataField: "supplierName",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "采购凭证号",
                            dataField: "poNum",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "行号",
                            dataField: "lineNumber",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "零件编号",
                            dataField: "itemCode",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "零件中文名",
                            dataField: "itemName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "驳回原因",
                            dataField: "adjustReason",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "驳回时间",
                            dataField: "supplierConfirmDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                    ]
                },
            };

            function getDscRejectDataList(curPage) {
                var service = "device";
                var reqUrl = "/dsc/listRejectOrders";
                
                if (!!curPage) {
                    $scope.dscRejectInfo.pageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.dscRejectInfo.pageInfo.pageSize,
                    pageNum: $scope.dscRejectInfo.pageInfo.curPage,
                    filters: angular.copy($scope.dscRejectInfo.condition)
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.supplierConfirmDateShow = $filter("YbDate")(item.supplierConfirmDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.dscRejectInfo.pageInfo.totalRows = resp.value.total;
                    $scope.dscRejectInfo.pageInfo.totalPages = resp.value.pages;
                    $scope.dscRejectInfo.dataList = resp.value.list;
                });
            }
            $scope.dscRejectOrders = function () {
                $scope.dscRejectInfo.pageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                }
                $scope.dscRejectInfo.dataList = [];
                $scope.dscRejectInfo.condition = {};
                getDscRejectDataList(1).then(() => {
                    $scope.changeTab(16);
                })
            };

            $scope.go2handle4dsc = function(item) {
                ybHttp.Get('device', '/purchaseRequest/itemDscRejectOrderWhenCreatePurchase', { id: item.id }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    $scope.orderObj = resp.value || {};

                    // 申请单位默认
                    $scope.orderObj.purchaseOrgName = $scope.curOrg.companyName;

                    // 申请时间默认
                    $scope.orderObj.createDate = new Date();

                    // 收货人、手机号、收货地址默认
                    setDefaultReceiver($scope.curUser.name);

                    // 订单类型默认
                    $scope.orderObj.purchaseOrdType = 'NB';
                    $scope.orderObj.purchaseOrdTypeDesc = '一般采购';

                    // 采购组默认
                    $scope.orderObj.purchaseGroup = $scope.curUser.purchaseGroup;
                    // 库区编码默认
                    $scope.orderObj.sapInArea = $scope.isWJ ? '9000' : '';
                    
                    $scope.changeTab(17);
                });
            };

            function getUrlParams(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                var parm = window.location.hash.split("?")[1];
                if (parm == null) return null;
                var r = parm.match(reg);
                if (r == null) return null;
                return unescape(r[2]);
            }

            (function () {
                
                if ($scope.curUser.loginName == '216867717607587840') { // 徐工集团工程机械股份有限公司建设机械分公司
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'price').isShow = false;
                }

                if ($scope.isJCHK) {
                    $scope.condition.countryVOS = $scope.curUser.associateCountryVOS;
                }

                if (!$scope.isZHJCH) {
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'deliveryDate').hidden = true;
                }

                if ($scope.isWJ) {
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'priceSchemeName').hidden = true;
                }

                getPurchaseLevel();
                getOrderStatues();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);

                var orderId = getUrlParams("orderId");
                var orderNo = getUrlParams("orderNo") || $stateParams.billNo;

                if (orderNo) {
                    $scope.condition.billNo = orderNo
                    getDataList();
                } else if (orderId) {
                    $scope.editApply({
                        billId: orderId
                    });
                }

                if (!$scope.isWJ) {
                    var defaultCreateDateStart = new Date();
                    defaultCreateDateStart = defaultCreateDateStart.setDate(defaultCreateDateStart.getDate() - 365);
                    $scope.condition.createDateStart = new Date(defaultCreateDateStart);
                }
                if ($scope.isJCHK) {
                    const countriesTmp = $scope.curUser.associateCountryVOS || [];
                    $scope.countries = countriesTmp.map(ct => ({ name: ct.countryName, code: ct.countryCode }));
                }
                const masterOrgIdsTemp = $scope.curOrg.masterOrgIds || [];
                const isJCHDlsh = masterOrgIdsTemp.some(cmo => window.JCH_ORG_IDs.includes(cmo)); // 当前登录账号是基础代理商
                if (isJCHDlsh) {
                    $scope.isJCHDlsh = true;
                }
            })();
        }]);
})(window, window.angular);
